from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .forms import IdcForm, HostForm
from .models import *

def index(request):
    #显示主页
    return render(request, 'cmdb/index.html')

def idcs(request):
    #显示所有机房
    idcs = Idc.objects.all()
    context = {'idcs': idcs}
    return render(request, 'cmdb/idcs.html', context)

def idc(request, idc_id):
    # 查看机房
    idc = Idc.objects.get(id=idc_id)
    hosts = idc.host_set.all()
    context = {'idc': idc, 'hosts': hosts}
    return render(request, 'cmdb/idc.html', context)

def new_idc(request):
    #添加机房
    if request.method !='POST':
        form = IdcForm
    else:
        form = IdcForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('cmdb:idcs'))
    context = {'form': form}
    return render(request, 'cmdb/new_idc.html', context)

def new_host(request, idc_id):
    #添加主机列表
    idc = Idc.objects.get(id=idc_id)
    if request.method != 'POST':
        form = HostForm
    else:
        form = HostForm(data=request.POST)
        if form.is_valid():
            new_host = form.save(commit=False)
            new_host.idc = idc
            new_host.save()
            return HttpResponseRedirect(reverse('cmdb:idc', args=[idc_id]))
    context = {'idc': idc, 'form': form}
    return render(request, 'cmdb/new_host.html', context)

def edit_host(request, host_id):
    #编辑条目
    hosts = Host.objects.get(id=host_id)
    idc = host.idc
    if request.method !='POST':
        form = HostForm(instance=hosts)
    else:
        form = HostForm(instance=hosts, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('cmdb:idc',args=[idc_id]))
    context = {'hosts': hosts, 'idc': idc, 'form': form}
    return render(request, 'cmdb/edit_host.html', context)
